<template>
  <el-dialog :title="formData.driverUuid ? '修改' : '添加'" width="70%" :model-value="dialog" @close="close">
    <el-form :model="formData" :rules="rules" ref="uploadForm" label-width="auto" style="padding: 0 20px" class="Dform">
      <div class="flex flex-wrap form-item-wrap">
        <el-form-item label="司机名称：" prop="name">
          <el-input v-model="formData.name" />
        </el-form-item>
        <el-form-item label="司机手机号：" prop="mobileNumber">
          <el-input v-model="formData.mobileNumber" />
        </el-form-item>
        <el-form-item label="性别：" prop="sex">
          <el-radio-group v-model="formData.sex">
            <el-radio :label="0">男</el-radio>
            <el-radio :label="1">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="司机所属方" prop="driverOwner">
          <el-select v-model="formData.driverOwner" filterable clearable style="width: 100%" placeholder="请选择司机所属方">
            <el-option :label="item.partnerName" :value="item.partnerUuid" v-for="item in partnerList"
              :key="item.partnerUuid" />
          </el-select>
        </el-form-item>
        <el-form-item label="司机身份证号：" prop="idCard">
          <el-input v-model="formData.idCard" @change="IdCardChange" />
        </el-form-item>
        <el-form-item label="年龄：" prop="age">
          <el-input v-model="formData.age" />
        </el-form-item>
        <el-form-item label="紧急联系人姓名：" prop="emergencyContactName">
          <el-input v-model="formData.emergencyContactName" />
        </el-form-item>
        <el-form-item label="紧急联系人手机号：" prop="emergencyContactPhone">
          <el-input v-model="formData.emergencyContactPhone" />
        </el-form-item>

        <el-form-item label="司机地址：" prop="areaCode">
          <area-code v-model:provinceCode="formData.provinceCode" v-model:cityCode="formData.cityCode"
            v-model:areaCode="formData.areaCode" showArea />
        </el-form-item>
        <el-form-item label="详细地址：" prop="address">
          <el-input v-model="formData.address" />
        </el-form-item>

        <el-form-item label="司机入职时间：" prop="entryTime">
          <el-date-picker v-model="formData.entryTime" type="date" value-format="x" style="width: 100%;" />
        </el-form-item>
        <el-form-item label="司机离职时间：" prop="dimissionTime">
          <el-date-picker v-model="formData.dimissionTime" type="date" value-format="x" style="width: 100%;" />
        </el-form-item>
        <el-form-item label="司机邮箱：" prop="email">
          <el-input v-model="formData.email" />
        </el-form-item>
      </div>
      <el-form-item>
        <el-button type="primary" @click="onSubmit()">提交</el-button>
        <el-button v-if="!formData.driverUuid" @click="resetForm()">重置</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script lang="ts">
import { defineComponent, ref, PropType, watch, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { updateDriver, saveDriver, queryProvinceDict } from '@/api/system'
import { driverStatusMap } from '@/config/constants'
import { partnerQuery } from "@/api/user"
import { validateMobile, validateIdCard } from '@/utils'
import AreaCode from '@/components/area-code/index.vue'
export default defineComponent({
  components: {
    AreaCode,
  },
  props: {
    dialog: {
      type: Boolean,
      default: false,
    },
    currentForm: {
      type: Object,
      default: () => { },
    },
    selectMenuList: {
      type: Array as PropType<{ title: string; id: string | number }[]>,
      default: () => [],
    },
  },
  emits: ['update:currentForm', 'update:dialog', 'refresh'],
  setup(props, context) {
    const formData = reactive(props.currentForm)
    const uploadForm = ref<any>(null)
    const options = ref<any>([])
    const partnerList = ref<any>([])

    watch(() => props.dialog,
      (val) => {
        Object.assign(formData, props.currentForm)
      }
    )

    const close = () => {
      context.emit('update:dialog', false)
      context.emit('refresh', { ...formData })
      context.emit('update:currentForm', {})
    }

    onMounted(() => {
      queryProvinceDict().then((res: any) => {
        options.value = res.data || []
      })
      formData.sex = Number(formData.sex)
      if (formData.entryTime) {
        formData.entryTime = new Date(formData.entryTime).toLocaleDateString()
      }
      if (formData.dimissionTime) {
        formData.dimissionTime = new Date(formData.dimissionTime).toLocaleDateString()
      }
      partnerQuery({ pageNum: 1, pageSize: 1000 }).then((res: any) => {
        partnerList.value = res.data.list || []
      })
    })

    //提取身份证号中的年龄
    const IdCardChange = (v: string) => {
      if (v && v.length >= 18) {
        formData.age = new Date().getFullYear() - Number(v.substring(6, 10))
      }
    }

    const onSubmit = () => {
      uploadForm.value.validate((valid: boolean) => {
        if (valid) {

          if (formData.driverUuid) {
            updateDriver(formData).then((res: any) => {
              if (res.code == 200) {
                ElMessage.success('修改成功')
                close()
              }
            })
          } else {
            saveDriver(formData).then((res: any) => {
              if (res.code == 200) {
                ElMessage.success('添加成功')
                close()
              }
            })
          }
        } else {
          ElMessage({
            message: '验证失败',
            type: 'error',
            duration: 1000,
          })
          return false
        }
      })
    }

    const resetForm = () => {
      uploadForm.value.resetFields()
      context.emit('update:currentForm', {})
    }

    return {
      uploadForm,
      formData,
      driverStatusMap,
      options,
      close,
      resetForm,
      IdCardChange,
      partnerList,
      onSubmit,
      rules: {
        name: [
          { required: true, message: '请输入司机名称', trigger: 'blur' }
        ],
        age: [
          { required: true, message: '请输入年龄', trigger: 'blur' }
        ],
        address: [
          { required: true, message: '请输入司机地址', trigger: 'blur' }
        ],
        mobileNumber: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: validateMobile, }
        ],
        emergencyContactName: [
          { required: true, message: '请输入紧急联系人姓名', trigger: 'blur' }
        ],
        emergencyContactPhone: [
          { required: true, message: '请输入紧急联系人手机号', trigger: 'blur' },
          { validator: validateMobile, }
        ],
        entryTime: [
          { required: true, message: '请选择入职时间', trigger: 'change' }
        ],
        // dimissionTime: [
        //   { required: true, message: '请选择离职时间', trigger: 'change' }
        // ],
        idCard: [
          { required: true, message: '请输入身份证号', trigger: 'blur' },
          { validator: validateIdCard, }
        ],
        areaCode: [
          { required: true, message: '请选择区县', trigger: 'change' }
        ],
        driverOwner: [
          { required: true, message: '请选择司机所属方', trigger: 'change' }
        ],
        // driverState: [
        //   { required: true, message: '请选择司机状态', trigger: 'change' }
        // ]
      },
    }
  },
})
</script>

<style lang="scss" scoped>
.form-item-wrap {
  column-gap: 20px;
}

:deep(.el-form-item) {
  width: 48%;
}
</style>
